<template>
  <div>
    <van-nav-bar class="van-app" title="登录/注册" left-arrow @click-left="$router.back()" />
    <!-- 登录 -->
    <van-form ref="formData" @submit="info" @failed="infoFaied" :show-error="false" :show-error-message="false" validate-first>
      <van-field
        v-model="user.mobile"
        icon-prefix="iconfont"
        left-icon="iconfont iconshouji"
        placeholder="请输入手机号" 
        :rules="formRules.mobile"
        name="modile"
        center
      />
      <van-field
        v-model="user.code"
        center
        icon-prefix="iconfont"
        left-icon="iconfont iconyanzhengma"
        clearable
        placeholder="请输入短信验证码"
        :rules="formRules.code"
        @click.prevent="onSendSms"
        
        
        
      >
        <template #button>
            <van-count-down @finish="isCountDownShow=false" :time="60*1000" format="ss s" v-if="isCountDownShow" />
          <van-button :loading="sendSmsloding" class="send-btn" size="mini" round type="primary" v-else>发送验证码</van-button>
        </template>
      </van-field>
    
    
    <div class="info-btn">
      <van-button type="info"  size="large" hairline>登录</van-button>
    </div>
    </van-form>
  </div>
</template>
<script>
import { logins,sendSms } from "@/api/user.js";

import { Toast } from "vant";
export default {
  data() {
    return {
      user: {
        mobile: "",
        code: "",
      },
      formRules:{
          mobile:[
               {required: true, message: '请填写电话号码' },
               {pattern:/^1[3|5|7|8|9]\d{9}$/,message:"手机格式错误"}
          ],
          code:[
              {required:true,message:"请输入验证码"},
              {pattern:/^\d{6}$/,message:"验证码格式错误"}
          ]
      },
      isCountDownShow:false,
      sendSmsloding:false

    };
  },
  methods: {
    //   登录事件
    async info() {
      Toast.loading({
        message: "登录中...",//提示文本
        forbidClick: true,//为true,就是说明，阻止点击背景
        duration:0//显示时间，0表示永久

      });

      try {
        const {data} = await logins(this.user); //登录接口
        Toast.success({
            message:'登录成功',
            position:'top'
        });
        this.$store.commit('setUser',data.data);//将后端返回的用户登录状态(token等数据)，放到Vuex容器中
        console.dir(data.data)
        this.$router.back();//路由后退

        // console.log(res);
      } catch (err) {
        console.dir(err);
        Toast.fail({
            message:'登录失败',
            position:"top"
        });
      }
    },
    //表单验证事件
    infoFaied(err){
        if (err.errors[0]){
            Toast.fail(
                {
                    message:err.errors[0].message,
                    position:"top"
                }
            );
        }else {
            Toast.fail({
                message:err.errors[1].message,
                position:"bottom"
            })
        }
        
        


    },
    // 短信验证码，发送事件
    
    async onSendSms(){
        try {
            this.sendSmsloding = true
            // 上面的代码是，防止在网速慢的时候，用户不知道已经发送短信验证码了，我们将button添加lodeing，防止用户第二次，第三次点击
            
             await this.$refs['formData'].validate("modile");
            
            
             await sendSms(this.user.mobile);
             this.isCountDownShow = true
            
            
            
        }catch (err){
            
            console.dir(err)
            var message = ""
            if (err.name == "modile"){

                message = err.message
                
                
            }else if (err && err.response.request.status == "429"){
                message = "请过一分钟，再发送试"

            }else {
                message = "其他错误"
            }
            
            Toast.fail({
                message,
                position:'top'
            })
            

        }
        this.sendSmsloding = false

    }

  },
};
</script>
<style scoped lang="less">
// .van-button__content {
.info-btn {
  padding: 26px 16px;
  opacity: 0.6;
  .van-button__text {
    font-size: 15px;
  }
}
.send-btn {
  width: 76px;
  height: 23px;

  background: #ededed;
  border: none;
  .van-button__text {
    font-size: 11px;

    color: #666666;
  }
}
// }
</style>